using FytSoa.Domain.Sys;
using FytSoa.Sugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using Masuit.Tools.Linq;
using Microsoft.AspNetCore.Mvc;

namespace FytSoa.Application.Sys
{
    /// <summary>
    /// 服务接口
    /// </summary>
    [ApiExplorerSettings(GroupName = "v1")]
    public class SysCodetypeService : SugarRepository<SysCodetype>,ISysCodetypeService 
    {
        private readonly IMapper _mapper;
        public SysCodetypeService(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        /// <summary>
        /// 查询所有——分页
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<SysCodetypeDto>>> GetPagesAsync(PageParam<CommonParam> param)
        {
            Expression<Func<SysCodetype, bool>> where = m => true;
            var (list,totalItems,totalPage) = await base.GetPageResultAsync(where, param.Page, param.Limit, m => m.Id);
            var result = new PageResult<SysCodetypeDto>()
            {
                Items = _mapper.Map<List<SysCodetypeDto>>(list),
                TotalItems = totalItems,
                TotalPages = totalPage
            };
            return JResult<PageResult<SysCodetypeDto>>.Success(result);
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<SysCodetypeDto>>> GetListAsync(WhereParam<CommonParam> param)
        {
            Expression<Func<SysCodetype, bool>> where = m => true;
            var list = await base.GetListAsync(where, m => m.Id);
            return JResult<List<SysCodetypeDto>>.Success(_mapper.Map<List<SysCodetypeDto>>(list));
        }

        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ApiResult<SysCodetypeDto>> GetAsync(long id)
        {
            return JResult<SysCodetypeDto>.Success(_mapper.Map<SysCodetypeDto>(await base.GetByIdAsync(id)));
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> AddAsync(SysCodetypeDto model)
        {
            if (model.ParentId != 0)
            {
                var paramModel = await base.GetByIdAsync(model.ParentId);
                model.Layer = paramModel.Layer + 1;
                model.ParentIdList = paramModel.ParentIdList + model.Id + ",";
            }
            else
            {
                model.ParentIdList = model.Id.ToString() + ',';
            }
            
            var upModel = await base.GetFirstAsync(m => true, m => m.Sort);
            if (upModel != null)
            {
                model.Sort = upModel.Sort + 1;
            }
            return JResult<bool>.Success(await base.InsertAsync(_mapper.Map<SysCodetype>(model)));
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ModifyAsync(SysCodetypeDto model)
        {
            if (model.ParentId != 0)
            {
                var paramModel = await base.GetByIdAsync(model.ParentId);
                model.Layer = paramModel.Layer + 1;
                model.ParentIdList = paramModel.ParentIdList + model.Id + ",";
            }
            else
            {
                model.ParentIdList = model.Id.ToString() + ',';
            }
            return JResult<bool>.Success(await base.UpdateAsync(_mapper.Map<SysCodetype>(model)));
        }

        /// <summary>
        /// 删除,支持多个
        /// </summary>
        /// <param name="ids">逗号分隔</param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> DeleteAsync(string ids)
        {
            var id = ids.StrToListLong();
            return JResult<bool>.Success(await base.DeleteAsync(m=>id.Contains(m.Id)));
        }

        /// <summary>
        /// 自定义排序
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> ColSort(SortParam param)
        {
            int a = 0, b = 0, c = 0;
                var list = await base.GetListAsync(m => m.ParentId == param.Parent, m => m.Sort, Common.Enum.OrderEnum.Asc);
                if (list.Count <= 0) return JResult<int>.Success();
                var index = 0;
                foreach (var item in list)
                {
                    index++;
                    if (index == 1)
                    {
                        if (item.Id != param.Id) continue;
                        if (param.Type != 1) continue;
                        a = item.Sort;
                        b = list[index].Sort;
                        c = a;
                        a = b;
                        b = c;
                        item.Sort = a;
                        await base.UpdateAsync(item);
                        var nitem = list[index];
                        nitem.Sort = b;
                        await base.UpdateAsync(nitem);
                        break;
                    }
                    if (index == list.Count)
                    {
                        if (item.Id != param.Id) continue;
                        if (param.Type != 0) continue;
                        a = item.Sort;
                        b = list[index - 2].Sort;
                        c = a;
                        a = b;
                        b = c;
                        item.Sort = a;
                        await base.UpdateAsync(item);
                        var nitem = list[index - 2];
                        nitem.Sort = b;
                        await base.UpdateAsync(nitem);
                        break;
                    }
                    if (item.Id != param.Id) continue;
                    if (param.Type == 1) //下降一位
                    {
                        a = item.Sort;
                        b = list[index].Sort;
                        c = a;
                        a = b;
                        b = c;
                        item.Sort = a;
                        await base.UpdateAsync(item);
                        var nitem = list[index];
                        nitem.Sort = b;
                        await base.UpdateAsync(nitem);
                        break;
                    }
                    else
                    {
                        a = item.Sort;
                        b = list[index - 2].Sort;
                        c = a;
                        a = b;
                        b = c;
                        item.Sort = a;
                        await base.UpdateAsync(item);
                        var nitem = list[index - 2];
                        nitem.Sort = b;
                        await base.UpdateAsync(nitem);
                        break;
                    }
                } 
                return JResult<int>.Success();
        }
    }
}
